package com.boxin.ims.modules.wechat.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.subject.Subject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.Weather;
import com.boxin.ims.modules.wechat.entity.WechatConfig;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.Witticism;
import com.boxin.ims.modules.wechat.service.PinYinService;
import com.boxin.ims.modules.wechat.service.UserBusinessService;
import com.boxin.ims.modules.wechat.service.UserDefineService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemRealm.Principal;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

@Service
public class WechatUtils implements ApplicationContextAware{
	private static Logger logger = Logger.getLogger(WechatUtils.class);

	/**
	 * 
	 * http://m.weather.com.cn/data/101090901.html
	 */
	public final static String WEATHER_URL = "http://m.weather.com.cn/data/"; 
	
	
	public final static String TESTING =  "";//" 系统全面调试中，我们会在这两天全面推出，到时会发送开始公告！现在您可以先在平台中学习下功能和中奖的效果，谢谢您的支持！";
	
	public final static String APP_ID = "wx725c695aa1bd3828";//"wx725c695aa1bd3828";	//APPID
	public final static String APP_SECRET = "e6a954ddffeb4fd7800f5950610c13cd";//"e6a954ddffeb4fd7800f5950610c13cd";	// SEC
	
	
	private static WechatMemberService wechatMemberService;
	private static UserBusinessService userBusinessService;
	private static UserDefineService userDefineService;
	private static PinYinService pinYinService;
	private static WechatDaoHelper wechatDaoHelper;
	
	
	public static void main(String[] args) {
		try {
			URL url = new URL(WechatUtils.WEATHER_URL);
			Document doc = 	Jsoup.parse(url, 100000);
			doc.toString();
			
		} catch (Exception e) {
			
		}
	}
	
	
	public static  String getWeatherJson(String code){
		
		String result = "";
		try {
			
			URL url = new URL (WEATHER_URL+code+".html") ;
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求的方式;
			conn.setRequestMethod("GET"); 
			// 设置可以读入 ;
			conn.setDoInput(true); 
			// 设置可以输出 ;
			conn.setDoOutput(true); 
			// 构建缓冲流 ;
			BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8"));
			String line = null ;
			while ( (line = br.readLine()) != null ) {
				result += line+"\n" ;     
			}    
		} catch (Exception e) {
			// TODO: handle exception
		}
	     
	     return result ;
	}
	
	
	public static  Weather convertJsonToWeather(JSONObject object){
		Weather weather = new Weather();
		weather.setCity(object.getString("city"));
		weather.setCityEn(object.getString("city_en"));
		weather.setCityId(object.getString("cityid"));
		weather.setDate(object.getString("date"));
		weather.setDateY(object.getString("date_y"));
		weather.setFchh(object.getString("fchh"));
		
		//<!-- 风速描述 -->    
		weather.setWind1(object.getString("wind1"));
		weather.setWind2(object.getString("wind2"));
		weather.setWind3(object.getString("wind3"));
		weather.setWind4(object.getString("wind4"));
		weather.setWind5(object.getString("wind5"));
		weather.setWind6(object.getString("wind6"));
		
		//<!-- 风速级别描述 -->   
		weather.setFl1(object.getString("fl1"));
		weather.setFl2(object.getString("fl2"));
		weather.setFl3(object.getString("fl3"));
		weather.setFl4(object.getString("fl4"));
		weather.setFl5(object.getString("fl5"));
		weather.setFl6(object.getString("fl6"));
		weather.setFx1(object.getString("fx1"));
		weather.setFx2(object.getString("fx2"));
		
		//<!-- 从今天开始到第六天的每天的天气情况，这里的温度是摄氏温度 -->  
		weather.setTemp1(object.getString("temp1"));
		weather.setTemp2(object.getString("temp2"));
		weather.setTemp3(object.getString("temp3"));
		weather.setTemp4(object.getString("temp4"));
		weather.setTemp5(object.getString("temp5"));
		weather.setTemp6(object.getString("temp6"));
		
		//<!-- 天气描述 -->    
		weather.setWeather1(object.getString("weather1"));
		weather.setWeather2(object.getString("weather2"));
		weather.setWeather3(object.getString("weather3"));
		weather.setWeather4(object.getString("weather4"));
		weather.setWeather5(object.getString("weather5"));
		weather.setWeather6(object.getString("weather6"));
		
		// <!-- 今天穿衣指数 -->   
		
		
		
		//<!-- 48小时穿衣指数 -->  
		
		return weather;
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-11  下午9:45:05
	 * @function <p> 获取用户合局配置 </p>
	 * @param userId
	 * @return
	 */
	public static UserDefine getUserDefineByUserId(Long userId){
		UserDefine userDefine = (UserDefine) getCache("UserDefine"+userId);
		if(userDefine == null){
			userDefine = userDefineService.getByUserId(userId);
			putCache("UserDefine"+userId, userDefine);
		}
		return userDefine;
	}
	
	
	
	
	
	public static String processUserBusinessReply(Long userId,String keywords,Object value){
		UserBusiness userBusiness = getUserBusinessByKeyWords(userId, keywords);
		if(userBusiness != null){
			String content = userBusiness.getContent();
			content = content.replaceAll("%"+userBusiness.getName()+"%", value.toString() );
			return content;
		}else{
			return null;
		}
	}
	
	
	public static UserBusiness getUserBusinessByKeyWords(Long userId,String keywords){
		UserBusiness userBusiness = (UserBusiness)getCache(userId+keywords);
		if(userBusiness == null){
			List<UserBusiness> businesses = userBusinessService.findAllByUserId(userId);
			for(UserBusiness ub : businesses){
				putCache(ub.getUser().getId()+ub.getBusinessConfig().getKeywords(), ub);
				if(ub.getUser().getId() == userId && keywords.equals(ub.getBusinessConfig().getName())){
					userBusiness = ub;
				}
			}
		}
		return userBusiness;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-20  上午12:15:28
	 * @function <p> 找到问题的相似答案  </p>
	 * @param configs
	 * @param upcon
	 * @return
	 */
	public static WechatConfig getConfigByUpContent(List<WechatConfig> configs,String upcon){
		if(configs != null && !configs.isEmpty()){
			
			for(WechatConfig config : configs){
				if(config.getUpContent()!=null && StringUtils.isNotEmpty(upcon)){
					if(config.getUpContent().trim().toLowerCase().contains(upcon.trim().toLowerCase())){
						return config;
					}
				}
			}
		}
		return null;
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-22  上午12:31:38
	 * @function <p>获取微信设置中上传的文件资源路径  </p>
	 * @return
	 */
	public static String getWechatResourceSavePath(){
		 return DictUtils.getDictValue("微信资源目录", "res_wp_path", "微信资源目录");
	}
	
	
	
	public static String getWechatResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "wechat";
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-26  下午4:00:07
	 * @function <p>微信秒杀上传文件存储路径  </p>
	 * @param request
	 * @return
	 */
	public static String getWechatSeckillResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "seckill";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-19  下午5:25:51
	 * @function <p> 广告系统中的图片存放位置  </p>
	 * @param request
	 * @return
	 */
	public static String getWechatAdvertResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "advert";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-5-5  下午6:00:19
	 * @function <p> 定是扫描 获得积分 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatTimingScoreResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "advert";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-26  下午4:00:07
	 * @function <p>微信秒杀上传文件存储路径  </p>
	 * @param request
	 * @return
	 */
	public static String getMicroProductResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "product";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-31  上午8:56:18
	 * @function <p> 微信会员卡生成路径 </p>
	 * @param request
	 * @return
	 */
	public static String getMemberCardResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "memberCard";
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-26  下午4:00:07
	 * @function <p>微信客服回复上传文件存储路径  </p>
	 * @param request
	 * @return
	 */
	public static String getWechatMassMediaResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "massmedia";
	}
	
	/**
	 * 自定义 积分活动页面资源存储路径
	 */
	public static String getCustomPageResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "pages";
	}
	
	/**
	 * 玖久
	 */
	public static String getHouseKeepingSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "jiu";
	}
	
	/**
	 * 慧思蒙 ---推送图片
	 */
	public static String getPicPath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "huisimeng"+File.separator+"pic";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-1-14  下午11:23:23
	 * @function <p> 业务、活动的资源存储路径 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatUserBusinessResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "business";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-27  下午11:19:13
	 * @function <p> 微网站存储路径 </p>
	 * @param request
	 * @return
	 */
	public static String getProjectResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "project";
	}
	
	public static String getDiancanQrcodeResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "diancanQrcode";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-27  下午11:19:13
	 * @function <p> 微购物存储路径 </p>
	 * @param request
	 * @return
	 */
	public static String getShoppingResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "shopping";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-27  下午11:19:13
	 * @function <p> 微网站存储路径 </p>
	 * @param request
	 * @return
	 */
	public static String getScoreExchangeProjectResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "score";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-14  下午4:59:13
	 * @function <p> 餐饮类图片存储位置 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatFoodResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "food";
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-4  下午2:18:51
	 * @function <p> 婚庆照片存储路径 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatWeddingScreenResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		
		return rootpath +File.separator + "wedding";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-4  下午2:18:51
	 * @function <p> 问卷调查图片 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatQuestionnaireSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		
		return rootpath +File.separator + "questionnaire";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-22  下午11:56:50
	 * @function <p> 注册会员的图片路径 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatRegMemberSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "images";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-31  下午10:49:48
	 * @function <p> 进入秒杀页面的微信消息图片链接图片存储路径 </p>
	 * @param request
	 * @return
	 */
	public static String getWechatSeckillLinkSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "seckill";
	}
	
	/**     
	 * 生成会员海报路径
	 * @param request
	 * @return
	 */
	public static String getPosterResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "poster";
	}
	
	/**     
	 * 慧思蒙渠道码
	 * @param request
	 * @return
	 */
	public static String getQcodSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "qcod";
	}
	
	
	/**
	 * 推广功能背景图片
	 * @param request
	 * @return
	 */
	public static String getRecommendSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "recommend";
	}
	


	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		wechatMemberService = (WechatMemberService)applicationContext.getBean("wechatMemberService");
		userBusinessService = (UserBusinessService)applicationContext.getBean("userBusinessService");
		userDefineService = (UserDefineService)applicationContext.getBean("userDefineService");
		pinYinService = (PinYinService)applicationContext.getBean("pinYinService");
		wechatDaoHelper = (WechatDaoHelper)applicationContext.getBean("wechatDaoHelper");
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-16  上午10:02:07
	 * @function <p> 获到微信绑定会员信息  </p>
	 * @param user
	 * @param openId
	 * @return
	 */
	public static  WechatMember getWechatMemberByOpenId(User user,String openId){
		WechatMember wechatMember = (WechatMember) getCache(user.getId()+openId);
		if(wechatMember == null){
			wechatMember = wechatMemberService.getByWechatMemberId(user, openId);
			if(wechatMember != null){
				putCache(user.getId()+openId, wechatMember);
			}
		}
		
		return wechatMember;
	}
	
	
	
	public static void initMemberCard(WechatMember member){
		if(member != null ){
			
		}else{
			
		}
	}
	
	
	
	
	
	/**
	 * 获取关键字
	 *@author xiaoqian
	 * @param key
	 * @return
	 * 2014-3-13下午2:31:34
	 */
	public static String getKeyWord(String upcon){
		String upconpy=PinyinUtils.getPinYin(upcon);
		String keyword = (String) getCache(upconpy);
		if(keyword == null){
			List<Map<String, Object>> list =  pinYinService.getKeyWord();
			for (int i = 0; i < list.size(); i++) {
				Object object=list.get(i).get("keywords");
				if(object==null){
					continue;
				}
				keyword=object.toString().trim();
				String pinyin=PinyinUtils.getPinYin(keyword);
				putCache(pinyin, keyword);
			}
		}
		keyword=(String) getCache(upconpy);
		if(keyword==null){
			return upcon;
		}
		return keyword;
	}
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getCacheMap().get(key);
		return obj==defaultValue?defaultValue:obj;
	}
	
	public static void putCache(String key, Object value) {
		getCacheMap().put(key, value);
	}
	
	public static void removeCache(String key) {
		getCacheMap().remove(key);
	}
	
	private static Map<String, Object> getCacheMap(){
		Map<String, Object> map = Maps.newHashMap();
		try{
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			return principal!=null?principal.getCacheMap():map;
		}catch (UnavailableSecurityManagerException e) {
			return map;
		}
	}

	/**
	 * share_type  是否共享
	 *@author xiaoqian
	 * @param newsReply
	 * @param category
	 * @return
	 * 2014-7-9上午9:38:08
	 */
	public static List<NewsReply>  getWitticism(NewsReply newsReply,String category,String shareType,Long userId){
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("share_type",shareType);
			params.put("category", category);
			params.put("user_id", userId);
			List<Witticism>  witticismList  = WechatInterfaceUtils.getWitticism();
			
			List<NewsReply>  newsReplieList = new ArrayList<NewsReply>();
			for (int i = 0; i < witticismList.size(); i++) {
				Witticism witticism = witticismList.get(i);
				
				NewsReply reply =new NewsReply();
				reply.setUrl("http://www.hdzhx.com/zxims/f/wechat/witticism/viewWitticism/"+witticism.getId()+"?from=cb");
				if(StringUtils.isEmpty(witticism.getPicUrl())){
					reply.setPicUrl("http://www.hdzhx.com/zxims/userfiles/images/xiaohua.jpg");
				}else{
					reply.setPicUrl(witticism.getPicUrl());
				}
				reply.setTitle(witticism.getTitle());
				reply.setDescription(witticism.getDescription());
				newsReplieList.add(reply);
			}
			return newsReplieList;
			
			
		} catch (Exception e) {
			e.getStackTrace();
			return null;
		}
	}
	

	/**
	 * 上传花卉图片存储路径
	  * @function 
	  * @author lzx
	  * @time 2014-11-14 下午4:37:03
	  * @param request
	  * @return
	 */
	public static String getFlowerResourceSavePath(HttpServletRequest request){
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "flower";
	}
	/**
	 * 网页授权(弹窗)
	 * @param url
	 * @param uid
	 * @param request
	 * @return
	 */
	public static String getOAuthUrl(String url, Long userId, HttpServletRequest request, HttpServletResponse response) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + path;
		WeChat weChat = WechatCacheUtils.getWeChatByUserId(userId);
		String state = userId + "";
		url = url.replace("null", "");
		CookieUtils.setCookie(response, "redirectUrl",basePath + Global.getFrontPath() + url);

		String redirectUrl = URLEncoder.encode(basePath + "/f/oauth/redirectUserinfo");
		System.out.println("redirectUrl====:"+redirectUrl);
		String returnUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ weChat.getAppId()	+ "&" + "redirect_uri="	+ redirectUrl + "&response_type=code&"
				+ "scope=snsapi_userinfo&state=" + state + "&connect_redirect=1#wechat_redirect";
		logger.info("网页授权(弹窗):" + returnUrl);
		
		return returnUrl;
	}


	/***
	 * 
	 * @function: <p>九号车间用户协议图片地址 </p>
	 * @param request
	 * @return
	 */
	public static String getNewsUpPath(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String rootpath = request.getRealPath("/userfiles");
		return rootpath +File.separator + "useragree";
	}
	
	
}
